package com.itic.mall.system.orders.item.service;

import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.common.service.CrudService;
import com.itic.appbase.framework.type.*;
import com.itic.appbase.framework.utils.DateHelper;
import com.itic.appbase.framework.utils.NumberStringHelper;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.mall.mobile.msg.vo.MsgVO;
import com.itic.mall.mobile.users.info.OrderItemVo;
import com.itic.mall.system.goods.goodssku.service.GoodsSkuService;
import com.itic.mall.system.goods.goodsspu.service.GoodsSpuService;
import com.itic.mall.system.goods.skucoupon.service.SkuCouponService;
import com.itic.mall.system.inter.goods.goodssku.persistence.model.GoodsSku;
import com.itic.mall.system.inter.goods.goodsspu.persistence.model.GoodsSpu;
import com.itic.mall.system.inter.goods.skucoupon.persistence.model.SkuCoupon;
import com.itic.mall.system.inter.orders.detail.persistence.model.OrdersDetail;
import com.itic.mall.system.inter.orders.item.persistence.dao.OrdersItemDao;
import com.itic.mall.system.inter.orders.item.persistence.model.OrdersItem;
import com.itic.mall.system.inter.orders.item.persistence.model.OrdersItemExample;
import com.itic.mall.system.inter.orders.orderJD.persistence.model.OrderJD;
import com.itic.mall.system.inter.orders.orderJDLeadInto.persistence.model.OrderJDLeadInto;
import com.itic.mall.system.inter.orders.orderJDProject.persistence.model.OrdersJDProduct;
import com.itic.mall.system.inter.pay.userlog.persistence.model.PayUserlog;
import com.itic.mall.system.inter.project.coupon.persistence.model.ProjectCoupon;
import com.itic.mall.system.inter.users.usercoupon.persistence.model.UsersCoupon;
import com.itic.mall.system.inter.users.usersmall.persistence.model.UsersMall;
import com.itic.mall.system.msg.apppush.service.AppPushService;
import com.itic.mall.system.orders.detail.service.OrdersDetailService;
import com.itic.mall.system.orders.orderJD.service.OrderJDService;
import com.itic.mall.system.orders.orderJDLeadInto.service.OrderJDLeadIntoService;
import com.itic.mall.system.orders.orderJDProject.service.OrdersJDProductService;
import com.itic.mall.system.pay.userlog.service.PayUserlogService;
import com.itic.mall.system.project.coupon.service.ProjectCouponService;
import com.itic.mall.system.users.usercoupon.service.UsersCouponService;
import com.itic.mall.system.users.usersmall.service.UsersMallService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


@Service
@Transactional
public class OrdersItemService
     extends CrudService<OrdersItemDao,OrdersItem,OrdersItemExample> {
	@Autowired
	private OrdersItemDao ordersItemDao;
    @Autowired
    private GoodsSpuService goodsSpuService;
    @Autowired
    private GoodsSkuService goodsSkuService;
    @Autowired
    private SkuCouponService skuCouponService;
    @Autowired
    private UsersCouponService usersCouponService;
    @Autowired
    private ProjectCouponService projectCouponService;
    @Autowired
    private OrdersDetailService ordersDetailService;

    @Autowired
    private PayUserlogService payUserlogService;
    @Autowired
    private UsersMallService usersMallService;
    @Autowired
    private AppPushService appPushService;
    @Autowired
    private OrderJDService orderJDService;
    @Autowired
    private OrderJDLeadIntoService orderJDLeadIntoService;
    @Autowired
    private OrdersJDProductService ordersJDProductService;
    
    private final static String PRICE ="PRICE";
    private final static String GOODCOUPON ="GOODCOUPON";
    /**
	 * 获取订单项信息
	 * @param orderNo
	 * @param skuId
	 * @return
	 */
	public OrdersItem getOrdersItem(String orderNo,String skuId){
		OrdersItem ordersItem = null;
		if(StringHelper.isNotBlank(orderNo) && StringHelper.isNotBlank(skuId)){
    		OrdersItemExample exampleg = new OrdersItemExample();
    		com.itic.mall.system.inter.orders.item.persistence.model.OrdersItemExample.Criteria criteriag = exampleg
    				.createCriteria();
    		criteriag.andIsEffectiveEqualTo(DBConst.TRUE);
    		criteriag.andOrderNoEqualTo(orderNo);
    		criteriag.andSkuIdEqualTo(skuId);
    		List<OrdersItem> listg = this.ordersItemDao.selectByExample(exampleg);
    		if(listg.size()>0){
    			ordersItem = listg.get(0);
    		}
    	}
		return ordersItem;
	}
    public OrderItemVo getOrderItemVo(String channel,String preType,String orderNo,String skuId){
		OrderItemVo orderItemVo = new OrderItemVo();
		String userId = "";
		String userPhone = "";
		Double wlCommission = null;
		Double wlCommissionShare = null;
		String goodsName = "";
		Date createTime = null;
		String userNickName = "";
		Double actualPay = null;
		String spuId = null;
		String itemDesc = null;
		if(StringHelper.isNotBlank(channel) && StringHelper.isNotBlank(preType) && StringHelper.isNotBlank(orderNo) && StringHelper.isNotBlank(skuId)){
			//预估收益渠道(C001：京选友惠，C002：天猫，C003：淘宝，C004：京东)
				if(StringHelper.isNotBlank(channel)){
					//友惠家订单
					if(channel.equals(PreIncomeChannel.yh.getState())){
						OrdersItem ordersItem = getOrdersItem(orderNo,skuId);
						if(ordersItem != null){
							actualPay = ordersItem.getActualPay();
							spuId = ordersItem.getGoodsId();
						}
						//获取商品信息
						if(StringHelper.isNotBlank(spuId)){
							GoodsSpu goodsSpu = goodsSpuService.get(spuId);
							if(goodsSpu != null){
								wlCommission = goodsSpu.getWlCommission();
								wlCommissionShare = goodsSpu.getWlCommissionShare();
							}
						}
		   				//获取订单项信息
		   				if(ordersItem != null){
		   					goodsName = ordersItem.getGoodsName();
		   				}
		   				//获取订单信息
		   				OrdersDetail ordersDetail = ordersDetailService.getOrdersDetailByOrderNo(orderNo);
		   				if(ordersDetail != null){
		   					userId = ordersDetail.getUserId();
		   					createTime = ordersDetail.getCreateTime();
		   				}
					}
					//天猫订单
					if(channel.equals(PreIncomeChannel.tm.getState())){
						
					}
					//淘宝订单
					if(channel.equals(PreIncomeChannel.tb.getState())){
						
					}
					//京东订单
					if(channel.equals(PreIncomeChannel.jd.getState())){
						String orderJDId = null;
						if(StringHelper.isNotBlank(preType)){
							//预计订单
							if(preType.equals(PreType.pre.getType())){
								OrderJDLeadInto orderJDLeadInto = orderJDLeadIntoService.getOrderJDLeadIntoByOrderNum(orderNo);
								if(orderJDLeadInto != null){
									createTime = orderJDLeadInto.getCreateTime();
									orderJDId = orderJDLeadInto.getId();
									userId = orderJDLeadInto.getUserId();
								}
							}
							//已结算订单
							if(preType.equals(PreType.actual.getType())){
								OrderJD orderJD = orderJDService.getOrderJDByOrderNum(orderNo);
								if(orderJD != null){
									createTime = orderJD.getCreateTime();
									orderJDId = orderJD.getId();
									userId = orderJD.getUserId();
								}
							}
						}
						OrdersJDProduct ordersJDProduct = ordersJDProductService.getOrdersJDItem(orderJDId,skuId);
						if(ordersJDProduct != null){
							goodsName = ordersJDProduct.getSkuName();
							wlCommission = Double.parseDouble(ordersJDProduct.getCommissions());
							wlCommissionShare = Double.parseDouble(ordersJDProduct.getCommissionRate());
							actualPay = Double.parseDouble(ordersJDProduct.getSkuPrice());
						}
					}
					
					//获取用户信息
					UsersMall usersMall = usersMallService.get(userId);
					if(usersMall != null){
						userNickName = usersMall.getUserNickName();
						userPhone = usersMall.getUserPhone();
					}
					//订单项描述信息
					itemDesc = "商品名称："+goodsName+"/n"
						  	  +"订单号："+orderNo+"/n"
						  	  +"日期："+DateHelper.formatDateTime(createTime)+"/n"
						  	  +"购买用户："+userNickName+"/n"
						  	  +"订单总金额："+actualPay+"/n"
						  	  +"佣金比例："+wlCommissionShare+"/n";
					orderItemVo.setUserPhone(userPhone);
					orderItemVo.setUserNickName(userNickName);
					orderItemVo.setGoodsName(goodsName);
					orderItemVo.setActualPay(actualPay);
					orderItemVo.setWlCommission(wlCommission);
					orderItemVo.setWlCommissionShare(wlCommissionShare);
					orderItemVo.setCreateTime(createTime);
					orderItemVo.setOrderNo(orderNo);
					orderItemVo.setUserId(userId);
					orderItemVo.setChannel(channel);
					orderItemVo.setOrderItemDesc(itemDesc);
				}
		}
		return orderItemVo;
	}
    
    /**
     * 根据订单号获取所有商品
     * @param orderNo
     * @param goodsId
     * @return
     */
    public List<OrdersItem> getOrderItemsByOrderNo(String orderNo){
    		OrdersItemExample exampleg = new OrdersItemExample();
			com.itic.mall.system.inter.orders.item.persistence.model.OrdersItemExample.Criteria criteriag = exampleg.createCriteria();
			criteriag.andIsEffectiveEqualTo(DBConst.TRUE);
			criteriag.andOrderNoEqualTo(orderNo);
			List<OrdersItem> list = this.list(exampleg);
			return list;
    }
    /**
     * 根据订单号和商品号获取订单详情
     * @param orderNo
     * @param goodsId
     * @return
     */
    public OrdersItem getorderItem(String orderNo,String goodsId){
    	OrdersItem ordersItem = null;
    	if(StringHelper.isNotBlank(goodsId) && StringHelper.isNotBlank(orderNo)){
    		OrdersItemExample exampleg = new OrdersItemExample();
			com.itic.mall.system.inter.orders.item.persistence.model.OrdersItemExample.Criteria criteriag = exampleg.createCriteria();
			criteriag.andIsEffectiveEqualTo(DBConst.TRUE);
			criteriag.andOrderNoEqualTo(orderNo);
			criteriag.andSkuIdEqualTo(goodsId);
			List<OrdersItem> list = this.ordersItemDao.selectByExample(exampleg);
			if(list.size()>0){
				ordersItem = list.get(0);
			}
    	}
    	return ordersItem;
    }
    /**
     * 根据订单项传入条件查询
     * @param item
     * @return
     */
    public OrdersItem ordersItem(OrdersItem item){
    	OrdersItem ordersItem = null;
    	if(item != null){
    		String orderNo = item.getOrderNo();
    		String skuId = item.getSkuId();
    		String goodsName = item.getGoodsName();
    		Date createTime = item.getCreateTime();
    		Date updateTime = item.getUpdateTime();
    		OrdersItemExample exampleg = new OrdersItemExample();
			com.itic.mall.system.inter.orders.item.persistence.model.OrdersItemExample.Criteria criteriag = exampleg.createCriteria();
			criteriag.andIsEffectiveEqualTo(DBConst.TRUE);
			criteriag.andOrderNoEqualTo(orderNo);
			criteriag.andSkuIdEqualTo(skuId);
			if(StringHelper.isNotBlank(goodsName)){
				criteriag.andGoodsNameEqualTo(goodsName);
			}
			if(createTime != null && updateTime != null){
				criteriag.andCreateTimeBetween(createTime, updateTime);
			}
			List<OrdersItem> list = this.ordersItemDao.selectByExample(exampleg);
			if(list.size()>0){
				ordersItem = list.get(0);
			}
    	}
    	return ordersItem;
    }
    /**
     * 添加订单中的商品
     * */
    public List<OrdersItem> addOrderItem(Map<String, String> skuMap,String orderNo,String yunId,String userId) {
    	List<OrdersItem> ordersItems = new ArrayList<>(skuMap.size());
    	// 计算每种商品的优惠价格  重新写算法
    	for(String key:skuMap.keySet()) {
    		GoodsSpu goodsSpu = this.goodsSpuService.getBySku(key);
    		OrdersItem ordersItem = new OrdersItem();
    		ordersItem.setSkuId(key);
    		int count = Integer.parseInt(skuMap.get(key));
    		// 计算每件商品的优惠价格
    		Map<String, Object> priceMap = this.calPrice(userId,goodsSpu.getIsGoodsCoupon(),key, count);
    		//实际价格
    		ordersItem.setActualPay((Double)priceMap.get(key));
    		ordersItem.setPrice((Double)priceMap.get(PRICE));
			ordersItem.setCount(count);
			ordersItem.setGoodsId(goodsSpu.getId());
			ordersItem.setGoodsImg(goodsSpu.getMainImageUrl());
			ordersItem.setGoodsName(goodsSpu.getGoodsName());
			ordersItem.setOrderNo(orderNo);
			ordersItem.setStoreId(yunId);
			ordersItem.setState(OrderType.Paying.getState());
			ordersItem.setIsServenBack(goodsSpu.getIsServenBack());
			ordersItem.setCouponId((String) priceMap.get(GOODCOUPON));
			ordersItem.setCouponPrice(0D);
			ordersItem.setIsSettle("0");
		/*	String result = this.add(ordersItem);
			if(SUCCESS.equals(result))*/
			ordersItems.add(ordersItem);
    	}
    	return ordersItems;
    }
    
    public Map<String, Object> calPrice(String userId,String isUserGoodCoupon,String key,int count) {
    	Map<String,Object> skuPrices = new HashMap<String, Object>();
    	GoodsSpu goodsSpu = this.goodsSpuService.getBySku(key);
		GoodsSku goodsSku = this.goodsSkuService.getSkuBySkuId(key);
		if(goodsSku!=null) {
			//sku价格
			double price = goodsSku.getSkuPrice();
			skuPrices.put(PRICE, price*count);
			//获取商品的优惠券
			SkuCoupon skuCoupon = this.skuCouponService.getSkuCouponByGoodId(goodsSpu.getId());
			if(StringUtils.isNotEmpty(isUserGoodCoupon) && "1".equals(isUserGoodCoupon)) {
				if(skuCoupon!=null){
					List<UsersCoupon> usersCoupons = this.usersCouponService.getUserCouponByUserIdAndCouponId(userId, skuCoupon.getId());
					if(!usersCoupons.isEmpty()) {
						UsersCoupon usersCoupon = usersCoupons.get(0);
						CouponType couponType = CouponType.getCouponType(skuCoupon.getType());
						price = this.calCouponMoney(couponType, price, usersCoupon);
						skuPrices.put(GOODCOUPON, usersCoupon.getCouponId());
					}
				}
			}
			skuPrices.put(key, price*count);
		}
    	return skuPrices;
    }
    public double calCouponMoney(CouponType couponType,double price,UsersCoupon usersCoupon) {
    	if(couponType!=null) {
			switch (couponType) {
			case pack:
			case coupon:
				price = price - (usersCoupon.getAmount() ==null?0:usersCoupon.getAmount());
				break;
			case fullcut:
				double fullMoney = usersCoupon.getUseCond()==null?0:usersCoupon.getUseCond();
				if(price >fullMoney)
					price = price- usersCoupon.getAmount();
				break;
			default:
				break;
			}
			price = price <=0?0:price;
			return price;
		}
    	return price;
    }
    
    public double calRefund(String orderNo,String goodId) {
    	OrdersDetail ordersDetail = this.ordersDetailService.getOrdersDetailByOrderNo(orderNo);
    	OrdersItem ordersItem = this.getOrdersItemBySpuIdAndOrderNo(goodId, orderNo);
    	double actualMoney = ordersItem.getActualPay();
    	List<OrdersItem> ordersItems = this.getOrderItemsByOrderNo(orderNo);
    	double sumMoney = 0;
    	for(OrdersItem item : ordersItems)
    		sumMoney +=item.getActualPay();
    	double couponMoney =0;
    	if(StringUtils.isNotEmpty(ordersDetail.getCouponId())) {
    		ProjectCoupon projectCoupon = this.projectCouponService.get(ordersDetail.getCouponId());
    		if(projectCoupon!=null)
    			couponMoney+=projectCoupon.getAmount();
    	}
    	if("1".equals(ordersDetail.getIsUsePoints())) {
    		//TODO 计算积分比例
    	}
    	double refundMoney=actualMoney-(couponMoney*actualMoney/sumMoney);
    	return refundMoney<=0?0:refundMoney;
    }
    
    public OrdersItem getOrdersItemBySpuIdAndOrderNo(String skuId,String orderNo) {
		OrdersItemExample example = new OrdersItemExample();
		com.itic.mall.system.inter.orders.item.persistence.model.OrdersItemExample.Criteria criteria
		= example.createCriteria();
		criteria.andIsEffectiveEqualTo(DBConst.TRUE);
		criteria.andSkuIdEqualTo(skuId);
		criteria.andOrderNoEqualTo(orderNo);
		List<OrdersItem> ordersItems = this.list(example);
    	if(ordersItems.isEmpty())
    		return null;
    	else
    		return ordersItems.get(0);
    }
    
    public OrdersItem   calItemCouponMoney(OrdersItem ordersItem,Double sumCouponMoney,Double actualMoney){
    	Double itemAcutalMoney = ordersItem.getActualPay();
    	String mulMoney = NumberStringHelper.mulString(itemAcutalMoney.toString(), sumCouponMoney.toString());
    	String couponMoneyStr = NumberStringHelper.divString(mulMoney, actualMoney.toString(), 2);
    	double couponMoney = Double.parseDouble(couponMoneyStr);
    	itemAcutalMoney = Double.parseDouble(NumberStringHelper.subtractString(itemAcutalMoney.toString(), couponMoneyStr));
    	ordersItem.setActualPay(itemAcutalMoney);
    	ordersItem.setCouponPrice(couponMoney); 
    	return ordersItem;
    }
    /***
     * 查询超过N天的订单项
     * @return
     */
    public List<OrdersItem>  findItemsOutofDay(){
    	int day =20;
    	List<OrdersItem> ordersItems = this.ordersItemDao.findNotSettleOrdersItems(day);
    	return ordersItems;
    }
    
    public void calActualOutOfDays() {
    	List<OrdersItem> ordersItems = this.findItemsOutofDay();
    	for(OrdersItem ordersItem : ordersItems) {
    		List<PayUserlog> payUserlogs = this.payUserlogService.getPreAmountByOrderNoAndSkuIdAndType(ordersItem.getOrderNo(), ordersItem.getSkuId(), PreType.pre);
    		if(!payUserlogs.isEmpty()) {
    			for(PayUserlog pay : payUserlogs) {
    				UsersMall usersMall = this.usersMallService.get(pay.getUserId());
    				PreIncomeType preIncomeType = PreIncomeType.getType(pay.getPreIncomeType());
    				PreIncomeChannel preIncomeChannel = PreIncomeChannel.getType(pay.getPreIncomeChannel());
    				this.payUserlogService.addProfitAmount(pay.getUserId(), ordersItem.getOrderNo(), PreType.actual, pay.getPreAmount(), preIncomeType, preIncomeChannel, ordersItem.getSkuId(), OperateType.add);
    				this.payUserlogService.addProfitAmount(pay.getUserId(), ordersItem.getOrderNo(), PreType.pre, pay.getPreAmount(), PreIncomeType.changeActual, preIncomeChannel, ordersItem.getSkuId(), OperateType.sub);
    				Double banlance = usersMall.getMoney()==null?0:usersMall.getMoney();
    				Double totalProfit = usersMall.getTotalProfit()==null?0:usersMall.getTotalProfit();
    				Double preProfit = usersMall.getPreProfit()==null?0:usersMall.getPreProfit();
    				Double amount = pay.getPreAmount();
    				String userBanlance =NumberStringHelper.addString(banlance.toString(), amount.toString());
    				String totalProfitStr = NumberStringHelper.addString(totalProfit.toString(), amount.toString());
    				String preProfitStr = NumberStringHelper.subtractString(preProfit.toString(),amount.toString());
    				usersMall.setMoney(Double.parseDouble(userBanlance));
    				usersMall.setTotalProfit(Double.parseDouble(totalProfitStr));
    				usersMall.setPreProfit(Double.parseDouble(preProfitStr));
    				this.usersMallService.edit(usersMall);
    				AlertType alertType = AlertType.actual;
    				this.appPushService.pushMsg(usersMall,alertType, null,new MsgVO(amount));
    			}
    			ordersItem.setIsSettle("1");
    			this.edit(ordersItem);
    		}
    	}
    }
    
    public String closeOrderItem(String orderNo,String skuId) {
    	String result = SUCCESS;
    	OrdersItem  ordersItem = this.getOrdersItemBySpuIdAndOrderNo(skuId, orderNo);
    	if(ordersItem!=null && OrderType.Judgeing.getState().equals(ordersItem.getState())) {
    		ordersItem.setState(OrderType.finished.getState());
    		result = this.edit(ordersItem);
    		List<OrdersItem> ordersItems =  this.getOrderItemsByOrderNo(orderNo);
    		OrdersDetail ordersDetail = this.ordersDetailService.getOrdersDetailByOrderNo(orderNo);
    		boolean flag = true;
    		for(OrdersItem item : ordersItems) {
    			OrderType orderType = OrderType.getOrderType(item.getState());
    			switch (orderType) {
				case Judgeing:
				case Exchangeing:
				case ReturnGoodsing:
				case Repairing:
				case Refunding:
				case OrderException:
					flag = false;
				}
    		}
    		if(flag) {
    			ordersDetail.setState(OrderType.finished.getState());
    			result = this.ordersDetailService.edit(ordersDetail);
    		}
    			
    	}
    	return result;
    }
    /***
     * 获取最近购买的订单的售后的次数
     * @param userId
     * @param date
     * @return
     */
    public int getUserShoppingCountByDays(String userId,Date date) {
    	//友惠家自营订单
    	//List<OrdersDetail> ordersDetails = this.ordersDetailService.findUserLateDateOrdersDetail(userId, date);
    	List<OrdersDetail> ordersDetails = this.ordersDetailService.findUserLateDateNotExistOrdersDetail(userId, date);
    	int count =0;
    	for(OrdersDetail ordersDetail : ordersDetails) {
    		List<OrdersItem> ordersItems = this.getOrderItemsByOrderNo(ordersDetail.getOrderNo());
    		if(this.checkIsAfterSale(ordersItems)) {
    			count++;
    		}
    	}
    	//TODO 京东订单
    	return count;
    }
    /**
     * 获取用户在友惠家的消费 以及佣金
     * @param userId
     * @param date
     * @return
     */
    public Map<String, Double> getUserYHJCommissionRateByDays(String userId,Date date){
    	Double consume = 0d;
    	Double commission = 0d;
    	List<OrdersDetail> ordersDetails = this.ordersDetailService.findUserLateDateOrdersDetail(userId, date);
    	for(OrdersDetail ordersDetail : ordersDetails) {
    		List<OrdersItem> ordersItems = this.getOrderItemsByOrderNo(ordersDetail.getOrderNo());
    		if(!this.checkIsAfterSale(ordersItems)) {
    			for(OrdersItem item : ordersItems) {
        			OrderType orderType = OrderType.getOrderType(item.getState());
        			switch (orderType) {
    	    			case Judgeing:
    	    				GoodsSku goodsSku  = this.goodsSkuService.get(item.getSkuId());
    	    				consume =consume+goodsSku.getSkuPrice()*item.getCount();
    	    				commission= commission+goodsSku.getSkuProfit()*item.getCount();
    	    				break;
        			}
        		}
    		}
    	}
    	Map<String, Double> result = new HashMap<>();
    	result.put("consume", consume);
    	result.put("commission", commission);
    	return result;
    }
    
    /***
     * 获取最近购买商品的佣金比例
     * @param userId
     * @param date
     * @return
     */
    public double getUserCommissionRateCountByDays(String userId,Date date) {
    	//友惠家自营订单
    	List<OrdersDetail> ordersDetails = this.ordersDetailService.findUserLateDateOrdersDetail(userId, date);
    	Double consume = 0d;
    	Double commission = 0d;
    	Map<String, Double> yhjCommissoon = this.getUserYHJCommissionRateByDays(userId, date);
    	consume = consume + yhjCommissoon.get("consume");
    	commission = commission+yhjCommissoon.get("commission");
    	//京东订单佣金比例
    	if (consume.intValue() ==0)
			consume = 1d;
    	String commissionRate = NumberStringHelper.divString(Double.toString(commission),Double.toString(consume),2);
    	return Double.parseDouble(commissionRate);
    }	
    /**
     * 查看订单下是否有售后订单
     * @param orderNo
     * @return
     */
    private boolean checkIsAfterSale(List<OrdersItem> ordersItems) {
    	boolean flag = false;
		for(OrdersItem item : ordersItems) {
			OrderType orderType = OrderType.getOrderType(item.getState());
			switch (orderType) {
    			case Exchangeing:
    			case Exchanged:
    			case ReturnGoodsing:
    			case ReturnGoodsed:
    			case Repairing:
    			case Repaired:
    			case Refunding:
    			case Refunded:
    				flag = true;
    				break;
			}
			if(flag)
				break;
		}
    	return flag;
    }
    
    /***
     * 获取最近的消费钱数
     * @param userId
     * @param date
     * @return
     */
    public double getUserConsumeByDays(String userId,Date date) {
    	//友惠家自营订单
    	List<OrdersDetail> ordersDetails = this.ordersDetailService.findUserLateDateOrdersDetail(userId, date);
    	Double consume = 0d;
    	for(OrdersDetail ordersDetail : ordersDetails) {
    		List<OrdersItem> ordersItems = this.getOrderItemsByOrderNo(ordersDetail.getOrderNo());
    		if(!this.checkIsAfterSale(ordersItems)) {
    			for(OrdersItem item : ordersItems) {
        			OrderType orderType = OrderType.getOrderType(item.getState());
        			switch (orderType) {
    	    			case Judgeing:
    	    				//GoodsSku goodsSku  = this.goodsSkuService.get(item.getSkuId());
    	    				//consume =consume+goodsSku.getSkuPrice();
    	    				consume =consume+item.getActualPay();
    	    				break;
        			}
        		}
    		}
    	}
    	//京东订单消费
    	return consume;
    }
    /**
     * 同意售后时，扣除预估收益
     * @param orderNo
     * @param skuId
     * @return
     */
    public String agreeAfterSalePreIncome(String orderNo,String skuId) {
    	String result = SUCCESS;
    	OrdersDetail ordersDetail = this.ordersDetailService.getOrdersDetailByOrderNo(orderNo);
    	String userId = ordersDetail.getYunUserId();
    	UsersMall usersMall = null;
    	if(StringUtils.isEmpty(userId)) {
    		usersMall = this.usersMallService.get(ordersDetail.getUserId());
    		userId = usersMall.getId();
    	}
    	usersMall = this.usersMallService.get(userId);
    	if(usersMall !=null) {
    		OrdersItem ordersItem = this.getorderItem(orderNo, skuId);
    		GoodsSku goodsSku = this.goodsSkuService.get(skuId);
    		result = this.payUserlogService.addUserTeamPreProfit(usersMall,Double.toString(goodsSku.getSkuProfit()) , TaxCompany.yh, orderNo, PreType.pre, PreIncomeChannel.yh,skuId,OperateType.sub,PreIncomeType.tradeColse,ordersItem.getCount());
    	}
		return result;
    }
    
   public double getUserTotalCommission(String userId) {
	   double commission = 0;
	   Map<String, Double> yhj = this.getUserYHJCommissionRateByDays(userId, null);
	   commission = commission + yhj.get("commisiion");
	   //TODO 获取JD的佣金
	   
	   return commission;
   }
}
